<?php
  $this->AddHook('before_other_work','cityreq');
  function cityreq($bot) {
    if ($bot->firstrun) {
	  $Name = "cityreq"; 
      $Version = "".cityreq_VERSION; 
      $Date = "".cityreq_DATE;
      $bot->ld->UpdatePluginVersion($bot, $Name, $Version, $Date );
        return;
  	  }
  	  $data = $bot->ld->GetPlSettings("cityreq");
  	  if (isset($data->cbcityreqrun) && ($data->cbcityreqrun == true)) {
      if (isset($data->selitems) && isset($data->cityreqitem) && isset($data->cntsel) && 
          isset($data->cntitem) && !empty($data->cityreqitem) && is_array($data->cityreqitem)) {
        $aitems = $data->cityreqitem;
      	$totitem = count($aitems);
      	if (($data->cntsel > 0) && ($data->cntitem > 0) && ($totitem > 0)) {
          if (!extension_loaded('curl')) {if (!dl('php_curl.dll')) {$bot->SendMsg('cityreq: CURL not loaded'); return;}}
          $targetitem = 'energy_3';
       	  $bot->SendMsg(' ');$bot->SendMsg('cityreq Start');
          $sel = (array)$data->selitems;
          $cntnow = $data->cntsel;
          $cntitem=$data->cntitem;
          $postdata = "cmfs_typeahead_req_form_0=Start+Typing+a+Name";
          $aboo = array();
          $howmany = $data->howmany;
          $iplace = array();
          $ncode = '';
          $nfbuid = '';
          $ncbsel = 'false';
          $nname = '';
          $smsg = '';
          $cnt = 1;
          $last = 0;
          foreach ($sel as $key => $boo) {
            unset($aboo);
            $aboo = (array)$boo;
            if (isset($aboo) && !empty($aboo)) {
          	  $ncode = ''.$key;
          	  $nfbuid = $aboo['fbuid'];
          	  $ncbsel = $aboo['cbsel'];
          	  $nname = $aboo['cname'];
          	  $nname = strtr($nname, ' ', '_');
          	  if ($ncbsel == 'true') {
          		$postdata .= "&ids%5B%5D=$nfbuid";
          		$smsg .= '['.$cnt.']'.$nfbuid.' ';
          		$cnt++;
          		$iplace[] = array('nzuid'=>$ncode, 'nfbuid'=>$nfbuid, 'nname'=>$nname, 'last'=>0);
          	  }
          	}
          }
          $bot->SendMsg('ask '.$howmany.'x'.$cntnow.'x'.$totitem.' help requests to: '.$smsg);
          $cnti = $totitem;
          $iserror = true;
          foreach ($aitems as $icode) {
              $itemcode = trim((string)$icode);
              $bot->SendMsg('['.$cnti.'] '.$itemcode);
              $cnti--;
              for ($i=$howmany; $i>0; $i--) {
        	    $bot->SendMsg('#'.$i);
        	    if (empty($itemcode)) {
        	      $bot->SendMsg('Error: Empty item code');
        	      break;
        	    }
          		$ferr1 = false;
          		$ferr2 = false;
          		$XmlCfgFile1 = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/")).
          		    "Profiles/".$bot->zySnuid."__Zy.xml";
          	    $XmlCfgFile2 =  getcwd()."/Profiles/".$bot->zySnuid."__Zy.xml";
          	    $XmlCfg = false;
          	    try {
          	      $XmlCfg = new Zend_Config_Xml($XmlCfgFile1);
          	    }
          	    catch (Exception $e) {
          	      $ferr1 = true;
          	    }
				if ($ferr1) {
          	      try {
          	        $XmlCfg = new Zend_Config_Xml($XmlCfgFile2);
          	      }
          	      catch (Exception $e) {
          	        $ferr2 = true;
            	  }
				}          	    
          	    if (($ferr1 && $ferr2) || ($XmlCfg === false) || (!isset($XmlCfg)) || (empty($XmlCfg))) {
          	      $bot->SendMsg('Error: Failed to open '."/Profiles/".$bot->zySnuid.'__Zy.xml');
                  break 2;
          	    }
          	    $url = "?action=default&itemName=".$targetitem."&view=app&ref=&requestType=level_up&zySnid=1";
          		$url .= "&zyAuthHash=".$XmlCfg->zyAuthHash;
          		$url .= "&zySig=".$XmlCfg->zySig;
          		$url .= "&overlayed=true";
          		list($usec, $sec) = explode(" ", microtime());
    			$dc = bcmul((float)$sec, (float)1000.0, 3);
    			$fr = bcmul((float)$usec, (float)1000.0, 3);
        		$url .= "&".floatval(bcadd($dc, $fr, 0));
        		$sreferer = "http://fb-0.cityville.zynga.com/flash.php?isOuterIframe=1&htmlFrameDest=request.php".$url;
                $url = "http://fb-0.cityville.zynga.com/request.php".$url;
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
                curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, false);
                curl_setopt($curl, CURLOPT_COOKIESESSION, true);
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                curl_setopt($curl, CURLOPT_POST, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_REFERER, $sreferer);
                curl_setopt($curl, CURLOPT_USERAGENT, $XmlCfg->UserAgent);
                curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate");
                curl_setopt($curl, CURLOPT_COOKIE, $XmlCfg->Cookie);   
                curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                 "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*",
                 "Accept-Language: en-us",
                 "Host: fb-0.cityville.zynga.com",
                ));
                $curlData = curl_exec($curl);
                $curlErrorStr = curl_error($curl);
                curl_close($curl);
                if ($curlErrorStr == '') { 
                  $bot->SendMsg('HTTP-GET completed');
                }
                else {
                  $bot->SendMsg($curlErrorStr);
                  break 2;
                }
                $pos1 = strpos($curlData, '<snml:request-form');
                $pos2 = strpos($curlData, '</snml:request-form');
                //in case of empty response due to connection/server problem
                if (($pos1 === false) || ($pos2 === false)) {
                  $bot->SendMsg('Error parsing response 1');
                  break 2;
                }
                $curlData = substr($curlData, $pos1, ($pos2-$pos1));
                $pos1 = strpos($curlData, 'action="');
                if ($pos1 === false) {
                  $bot->SendMsg('Error parsing response 2');
                  break 2;
                }
          	    $pos1 += 8;
          	    $curlData = substr($curlData, $pos1);
          	    $pos2 = strpos($curlData, '"');
          	    if (($pos2 === false) || ($pos2 <= 0)) {
                  $bot->SendMsg('Error parsing response 3');
                  break 2;
                }
                $curlData = substr($curlData, 0, $pos2);
                $curlData = str_replace($targetitem, $itemcode, $curlData);
          	    $url = trim($curlData);
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
                curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, false);
                curl_setopt($curl, CURLOPT_COOKIESESSION, true);
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_REFERER, "http://www.facebook.com/plugins/serverfbml.php");
                curl_setopt($curl, CURLOPT_USERAGENT, $XmlCfg->UserAgent);
                curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate");
                //curl_setopt($curl, CURLOPT_COOKIE, "zy_login=1");
                curl_setopt($curl, CURLOPT_COOKIE, $XmlCfg->Cookie);
                curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                 "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*",
                 "Accept-Language: en-us",
                 "Content-Type: application/x-www-form-urlencoded",
                 //"Host: ".$bot->headers['Host'],
                 "Host: fb-client-0.cityville.zynga.com",
                 "Content-Length: ".strlen($postdata),
                 "Pragma: no-cache",
                ));
                curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
                $curlData = curl_exec($curl);
                $curlErrorStr = curl_error($curl);
                curl_close($curl);
                if ($curlErrorStr == '') { 
                  $bot->SendMsg('HTTP-POST completed');
                  $iserror = false; 
                }
                else {
                  $bot->SendMsg($curlErrorStr);
                  break 2;
                }
          	  }
          	  $bot->ReloadConfig();
          }
          $last = time();
          $data->cbcityreqrun = false;    //always reset
          $data->howmany = "1";
          $dlast = array();
          if (!$iserror) {
            foreach ($iplace as $k => $n) {
              $iplace[$k]['last'] = $last;
              $dlast[$n['nzuid']] = $last;
            }
          }
          else {$bot->ReloadConfig();}
          $data->last = array_merge((array)$data->last, $dlast);
  		  $bot->ld->SavePlSettings("cityreq", $data);
  		  sleep(1);
  		  $timenow = gmdate("Y_m_d_His");
  		  $txt = "Requests you sent to dummy-neighbors in -cityreq- plugin:\n".
                 "File DateTime: ".gmdate("Y F j, h:i A")." GMT\n".
  			     "Request DateTime: ".gmdate("Y F j, h:i A", $last)." GMT\n".
  			     "STATUS: ".($iserror?"ERROR":"OK")."\n".
  			     "---------------------------------------------------------\n".
  			     "Neighbors: (".$howmany." requests per neighbor)\n";
  		  $cnt = 1;
  		  foreach ($iplace as $n) {
  			$txt .= "(".$cnt.") ZUID-".$n['nzuid']." FBUID-".$n['nfbuid']." ".$n['nname']."\n";
  			$cnt++;
  		  }
  		  $txt .= "---------------------------------------------------------\n";
  		  $txt .= "ITEM codename:\n";
  		  foreach ($aitems as $itm) {
  		    $txt .= trim((string)$itm)."\n";
  		  }
  		  $txt .= "---------------------------------------------------------\n";
  		  try {
  			$cRDir = 'tmp_dir/cityreq/';
       	    if (!is_dir($cRDir)) { @mkdir($cRDir, 0777, true);  }
            $fname = $cRDir.'cR_'.$timenow.'_'.$bot->zySnuid.'_'.$bot->usern.'.txt';
            $f = fopen($fname, 'w');
            fwrite($f, $txt);
            fclose($f);
  		  }
  		  catch (Exception $e) { $bot->SendMsg('write to tmp_dir\cityreq\ error'); }
  		  $bot->pm->RefreshMePlugin("cityreq");
  		  $bot->SendMsg('cityreq End');$bot->SendMsg(' ');
    	}
  	  }
    }
  }
?>